/**
 * Created by yx on 2017/7/12.
 */
// var $tbody = $("#sample-table-1 tbody");
// jQuery(function ($) {
//     $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
//         $(this).prev().focus();
//     });
// });
var allStation = [];
var nowdate = new Date();
var oneweekdate = new Date(nowdate-7*24*3600*1000);

//全局变量，保存数据长度用于表格最后一条的向下按钮置灰
var dataLength = 0;
// $("#startdate").val(beginDate(oneweekdate));
// $("#enddate").val(endDate(nowdate));

function beginDate(date) {
    return endDate(date);
};

function endDate(date) {
    return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2);
};
console.log('industryManage');
// getAllInfo().done(function() {
// 初始化table
$("#industry_table").bootstrapTable({
    // 'url': '../serviceType/findAll',
    'url': '/user/job/findJobs',
    'toolbar': $('div[data-name="btnCtl"]'),
    // 'queryParams': queryParams,
    'cache':false,
    'sidePagination': 'server',
    'toolbarAlign': 'right',
    'undefinedText': '-',
    'striped': true,
    'pagination': true,
    'sortable': true, //是否启用排序
    'sortOrder': "asc", //排序方式
    'pageSize': globalPageSize,
    // 'pageList': [],
    'clickToSelect': false,
    'singleSelect': true,
    'smartDisplay': true,
    'ajaxOptions':{
        headers: {"Authorization": localStorage.token}
    },
    'responseHandler': function (resb) {
        console.log(resb);
        dataLength = resb.data.total;
        return {
            'total': resb.data.total,
            'rows': resb.data.content
        }
    },
    'onCheck': function() {
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
    },
    'onUncheck': function() {
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
    },
    'onPageChange': function() {
        if($("#industry_table").bootstrapTable('getSelections')[0]){
            $("#industry_table").bootstrapTable('uncheckBy', {
                field: 'typeId',
                values: [$("#industry_table").bootstrapTable('getSelections')[0].typeId]
            });
        }

    },
    'columns': [{
        'checkbox': true,
        // 'class': 'hide'
    },
        {
            'field': 'jobId',
            'title': '职业ID',
            'align': 'center',
            'class': 'hide id'
        },{
            'field': 'name',
            'title': '职业名称',
            'align': 'center'
        },{
            'field': 'createTime',
            'title': '创建日期',
            'align': 'center'
        },{
            'field': 'sort',
            'title': '显示顺序',
            'align': 'center'
        },{
            'field': 'state',
            'title': '状态',
            'align': 'center',
            'formatter': function (state) {
                var obj = {'1':'显示','0':'隐藏'};
                var html = "<button class='btn btn-sm btn-success labToggleShow' data-state="+state+">"+obj[state]+"</button>";
                return html;
            }
        }, {
            'title': '操作',
            'align': 'center',
            'valign': 'middle',
            'formatter': function (value, row) {
                var html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' data-type='up' style='margin-right: 30px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down'></button>";
                //将第一个tr的向上按钮置灰
                if(row.sort === 1) {
                    html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' disabled data-type='up' style='margin-right: 30px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down'></button>";
                }
                if(row.sort === dataLength) {
                    html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' data-type='up' style='margin-right: 30px'></button><button disabled class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down'></button>";
                }
                return html;
            }
        }
    ]
});
// });

//请求服务数据时所传参数
function queryParams(params){
    return {
        'name': $('#desc').val(),
        // 'labelStatus' : $('#signStatus').val(),
        // 'createDateS': $('#startdate').val(),
        // 'createDateE' : $('#enddate').val(),
        limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
        offset : params.offset //当前页面,默认是上面设置的1(pageNumber)
    }
}

/**
 * 猿粪查询ajax
 * @param name 请求查询的服务人员名称
 */
function industryQuery() {
    if($("#contentName").val()== ''&&$("#startdate").val()== ''&&$("#enddate").val()== ''&&$(".selectClassify").val()==''){
        $('#industry_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
    }else{
        $('#industry_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
        $.ajaxSetup({cache:false});
        $.ajax({
            type: "GET",
            // url: "/community/forummessage/getFindMsg",
            url: "/user/job/findJobs?name="+$('#desc').val()+"&limit="+globalPageSize+"&offset=0",
            dataType: 'json',
            // contentType: "application/json",
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", localStorage.token);
            },
            success: function(resb) {
                console.log(resb);
                if (resb.data.length != 0) {
                    $("#industry_table").bootstrapTable('load', {
                        'total': resb.data.total,
                        'rows': resb.data.content
                    });
                } else {
                    $("#industry_table").bootstrapTable('removeAll');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
}

/**
 * 列表操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
function industryManagement(action, data, async) {
    var url = null;
    var obj = {'add': '新增', 'update': '修改'};
    (async === false) ? async = false: async = true;
    if (action === 'add') {
        url = '/user/job/addJob?'+objTostring(data);
    } else if(action === 'update'){
        url = '/user/job/updateJob?'+objTostring(data);
    }else {
        url = '/user/job/deleteJob?'+objTostring(data);
    }
    return $.ajax({
        type: "GET",
        url: url,
        // data: JSON.stringify(data),
        contentType: "application/json",
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        async: async,
        success: function(resb) {
            alert(obj[action] + resb.message);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    });
}

function objTostring(obj) {
    var arr = [];
    for(var i in obj) {
        arr.push(i+"="+obj[i]);
    }
    console.log(arr.join('&'));
    return arr.join('&');
}

/**
 * 切换显示与隐藏
 */
$('.row').on('click', '.labToggleShow', function(){
    var data = {
        'jobId': $(this).parent().siblings('.id').html(),
        'state': 0
    };
    if($(this).attr('data-state') === '0') {
        data = {
            'jobId': $(this).parent().siblings('.id').html(),
            'state': 1
        }
    };
    var that = $(this);
    $.ajax({
        type: "GET",
        url: '/user/job/updateJob?'+objTostring(data),
        contentType: "application/json",
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function(resb) {
            console.log(resb);
            if(resb.success) {
                $('#industry_table').bootstrapTable('refresh');
                // that.html() === '显示' ? that.html('隐藏') : that.html('显示');
                // that.attr('data-state') === '0' ? that.attr('data-state', '1') : that.attr('data-state', '0');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    })
});

/**
 * 变换顺序
 */
$('#industry_table').off('click').on('click','.up, .down',function(){
    var  tableData = $("#industry_table").bootstrapTable("getSelections")[0];
    console.log(tableData);
    var action = ($(this).attr('data-type') === 'up' ? 'sortMoveUp' : 'sortMoveDown') + '?';
    var data = {
        'jobId': $(this).parent().siblings('.id').html()
    };
    // if($(this).attr('data-type') === 'up') {
    //     data = {
    //         'jobIdA': $(this).parent().siblings('.id').html(),
    //         'jobIdB': $(this).parent().parent().prev().find('.id').html()
    //     }
    // }
    $.ajax({
        type: "GET",
        url: '/user/job/' + action  +objTostring(data),
        contentType: "application/json",
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function(resb) {
            console.log(resb);
            // alert(resb.message);
            if(resb.success) {
                $('#industry_table').bootstrapTable('refreshOptions',{pageSize:globalPageSize});
            }else {
                alert(resb.message);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    })
    return false;
});

/**
 * 查询表单提交
 */
$("#dataSearch").on('click',function() {
    return industryQuery();
});

/**
 * 新增模态框显示
 */
$("#addModal").on('show.bs.modal', function() {
    $(this).find("input[type=text]").val("");
});

/**
 * 新增模态框显示
 */
$("#updateModal").on('show.bs.modal', function() {
    var  tableData = $("#industry_table").bootstrapTable("getSelections")[0];
    $("#upDateId").val(tableData.jobId);
    $("#upDateName").val(tableData.name)
});

/**
 * 删除模态框显示
 */
$("#deleteModal").on('show.bs.modal', function() {
    var name = $("#industry_table").bootstrapTable('getSelections')[0].name;
    var html = '是否删除'+name+'?';
    $(this).find('div.modal-body').empty().append(html);
});

/**
 * 新增,更新,删除角色表单提交
 */
$("button[name=submit]").on('click',function() {
    var obj = $("#addForm, #upDateForm").validationEngine('validate', {
        promptPosition: "centerRight",
        scroll: false,
        autoPositionUpdate: true,
        validationEventTrigger:'blur',
        binded:true,
        autoHidePrompt: true,
        autoHideDelay: 3000,
        showOneMessage:true
    });
    if (!obj) {
        return false;
    };
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        $inputs = $modal.find('input[type="text"]'),
        $selects = $modal.find('select')


    //$checkboxs = $(this).find('input[type="checkbox"]').prop('checked',true),
    tableData = $("#industry_table").bootstrapTable("getSelections")[0],
        data = null,
        $that = $(this);


    // 模式选择,设置不同的data和url
    if (type === 'delete') {
        data = {
            'jobId': tableData.jobId
        };
    } else if (type === 'add') {
        // var obj = jQuery("#addForm").validationEngine('validate', {promptPosition : "centerRight", autoPositionUpdate : true});
        // if(!obj){
        //     return false;
        // };
        // var $status = $modal.find('select[name="status"]');
        // var $orderNo = $modal.find('select[name="orderNo"]');
        data = {
            'name': $('#addName').val()
        };
    } else if (type ==='update') {
        var $status = $modal.find('select[name="status"]');

        data = {
            'jobId': $("#upDateId").val(),
            'name': $("#upDateName").val()
        };
    };


    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    industryManagement(type, data).done(function() {
        $("#industry_table").bootstrapTable("refresh");
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        $that.parents('.modal-content').find('form')[0].reset();
    });

    // 阻止表格冒泡事件
    return false;
});
